package servlet;
import java.io.File;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;

import org.lxh.smart.SmartUpload;



public class UploadServlet extends BaseServlet{
	private ServletConfig config;
    //初始化Servlet
    final public void init(ServletConfig config)
                throws ServletException{
    this.config=config;
    }
	/**
	 * 
	 */
	private static final long serialVersionUID = -8538076142868886263L;
	
	public void service() throws Exception{
		//图片绝对目录
		String path = request.getSession().getServletContext().getRealPath("/img/upload");
		//del标记，判断是否删除上传的文件
		boolean success = false;
		//文件上传
		SmartUpload su = new SmartUpload() ;
		//上传初始化
		su.initialize(config,request,response);
		//限制上传文件的最大长度 2M
		su.setMaxFileSize(2000000*8);
		//设定允许上传的文件（通过扩展名限制）
		try{
			su.setAllowedFilesList("jpg,gif,png,JPG,GIF,PNG");
		}catch(Exception ex){
			System.out.println("拓展名异常："+ex);
		}
		//准备上传文件
		try{
			su.upload() ;
		}catch(Exception ex){
			System.out.println("上传异常："+ex);
		}
		String picname = "index.jpg" ;
		String picurl = "index.jpg" ;
		File filePath = new File(path);
		if(!filePath.exists()){
			filePath.mkdirs();
		}
		
		//判断是否有附件上传
		for(int i=0; i<su.getFiles().getCount(); i++){
			org.lxh.smart.File file = su.getFiles().getFile(i);
			java.text.SimpleDateFormat dateFormatter = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
			String sNowTime = dateFormatter.format(new java.util.Date());
			picurl = sNowTime+"."+ file.getFileExt();
			picname = file.getFileName();
			file.saveAs("img/upload/"+picurl);
			success=true;
		}
		if(success){response.getWriter().write("{\"success\":true,\"url\":\""+picurl+"\",\"name\":\""+picname+"\"}");}
	}
}
